//
//  PhotoSelectManager.m
//  TestPinBang
//
//  Created by Hepburn Alex on 13-5-30.
//  Copyright (c) 2013年 Hepburn Alex. All rights reserved.
//

#import "PhotoSelectManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>


#ifndef SAFE_RELEASE

#if __has_feature(objc_arc)
#define SAFE_RELEASE(x)
#else
#define SAFE_RELEASE(x) ([(x) release])
#endif

#endif

#ifndef SAFE_SUPER_DEALLOC

#if __has_feature(objc_arc)
#define SAFE_SUPER_DEALLOC()
#else
#define SAFE_SUPER_DEALLOC() ([super dealloc])
#endif

#endif

#ifndef SAFE_AUTORELEASE

#if __has_feature(objc_arc)
#define SAFE_AUTORELEASE(x) x
#else
#define SAFE_AUTORELEASE(x) ([(x) autorelease])
#endif

#endif


@implementation PhotoSelectManager{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
}

@synthesize mRootCtrl, miWidth, miHeight, mbEdit,popoverController;

- (id)init {
    self = [super init];
    if (self) {
        mbEdit = YES;
        miWidth = 400;
        miHeight = 550;
        _mQuality = 0.95;
        self.mRootCtrl = [self getCurrentVC];
        self.maxImagesCount = 9;
        _selectedPhotos = [NSMutableArray array];
        _selectedAssets = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc {
    self.mRootCtrl = nil;
    SAFE_SUPER_DEALLOC();
}
- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.mRootCtrl.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.mRootCtrl.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedIn:[TZImagePickerController class], nil];
            BarItem = [UIBarButtonItem appearanceWhenContainedIn:[UIImagePickerController class], nil];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}



- (void)takePhoto {
    if (self.maxImagesCount == 1) {
        [_selectedAssets  removeAllObjects];
        [_selectedPhotos removeAllObjects];
    }
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS7Later) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        [alert show];
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        if (iOS7Later) {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        [self takePhoto];
                    });
                }
            }];
        } else {
            [self takePhoto];
        }
        // 拍照之前还需要检查相册权限
    } else if ([TZImageManager authorizationStatus] == 2) { // 已被拒绝，没有相册权限，将无法保存拍的照片
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法访问相册" message:@"请在iPhone的""设置-隐私-相册""中允许访问相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        alert.tag = 1;
        [alert show];
    } else if ([TZImageManager authorizationStatus] == 0) { // 未请求过相册权限
        [[TZImageManager manager] requestAuthorizationWithCompletion:^{
            [self takePhoto];
        }];
    } else {
        [self pushImagePickerController];
    }
}

// 调用相机
- (void)pushImagePickerController {
    // 提前定位
    __weak typeof(self) weakSelf = self;
    [[TZLocationManager manager] startLocationWithSuccessBlock:^(NSArray<CLLocation *> *locationArray) {
        if(locationArray.count > 0){
            weakSelf.location = locationArray[0];
        }
    } failureBlock:^(NSError *error) {
        weakSelf.location = nil;
    }];
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        self.imagePickerVc.sourceType = sourceType;
        if(iOS8Later) {
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self.mRootCtrl presentViewController:_imagePickerVc animated:YES completion:nil];
    } else {
        NSLog(@"模拟器中无法打开照相机,请在真机中使用");
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo: (NSDictionary *) info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = YES;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:self.location completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager]getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:YES completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        if (self.mbEdit) { // 允许裁剪,去裁剪
                            TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assetModel.asset photo:image completion:^(UIImage *cropImage, id asset) {
                                [self refreshCollectionViewWithAddedAsset:asset image:cropImage];
                                
                            }];
                            imagePicker.circleCropRadius = 100;
                            [self.mRootCtrl presentViewController:imagePicker animated:YES completion:nil];
                        } else {
                            [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
                            
                        }
                    }];
                }];
            }
        }];
    }
    
    //    // 图片类型
    //    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //    if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
    //        UIImage* image = nil;
    //        if (mbEdit) {
    //            image = [info objectForKey:UIImagePickerControllerEditedImage];
    //        }
    //        else {
    //            image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //        }
    //        
    //    }
    //    else if ([mediaType isEqualToString:(NSString*)kUTTypeVideo] || [mediaType isEqualToString:(NSString*)kUTTypeMovie]) {
    //        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL] ;
    //        NSLog(@"found a video %@", videoURL);
    //        
    //        NSString *videoPath = self.mLocalPath;
    //        if([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
    //            [[NSFileManager defaultManager] removeItemAtPath:videoPath error:nil];
    //        }
    //        [[NSFileManager defaultManager] copyItemAtPath:videoURL.path toPath:videoPath error:nil];
    //        
    //        if (delegate && _OnVideoSelect) {
    //            SafePerformSelector([delegate performSelector:_OnVideoSelect withObject:self]);
    //        }
    //    }
    //    [picker dismissViewControllerAnimated:YES completion:nil];
    ////    if (IsiPad) {
    ////        [popoverController dismissPopoverAnimated:YES];
    ////    }
}
-(void)TakeAlbum{
    //[_mPhotoManager TakePhoto:NO];
    TZImagePickerController *ctrl = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maxImagesCount delegate:nil];
    if (self.maxImagesCount == 1) {
        [_selectedAssets  removeAllObjects];
        [_selectedPhotos removeAllObjects];
        ctrl.allowCrop = YES;
    }
    ctrl.selectedAssets = _selectedAssets;
    ctrl.didFinishPickingPhotosWithInfosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        _selectedPhotos = [NSMutableArray arrayWithArray:photos];
        _selectedAssets = [NSMutableArray arrayWithArray:assets];
        if (self.PhotoFinishBlock) {
            self.PhotoFinishBlock(_selectedPhotos);
        }
        
    };
    [mRootCtrl presentViewController:ctrl animated:YES completion:nil];
    
}
#pragma mark - 照片存本地相册
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    //    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    //    UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil);
}


-(void)showAlert:(NSString *)title{
    UIAlertController *mAlertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [mAlertController addAction:cancelAction];
    [mAlertController addAction:okAction];
    [mRootCtrl presentViewController:mAlertController animated:YES completion:nil];
}

- (UIViewController *)getCurrentVC{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC{
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        currentVC = rootVC;
    }
    return currentVC;
}
- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image {
    [_selectedAssets addObject:asset];
    [_selectedPhotos addObject:image];
    if (self.PhotoFinishBlock) {
        self.PhotoFinishBlock(_selectedPhotos);
    }
}
-(void)delectImageWithIndex:(NSInteger)index{
    [_selectedAssets removeObjectAtIndex:index];
    [_selectedPhotos removeObjectAtIndex:index];
    if (self.PhotoFinishBlock) {
        self.PhotoFinishBlock(_selectedPhotos);
    }
}

@end
